<template>
  <v-dialog v-model="dialogFormVisible" max-width="800px" persistent>
    <v-card>
      <v-card-title>
        <span>{{ title }}</span>
      </v-card-title>

      <v-card-text>
        <v-form ref="formRef" v-model="valid">
          <v-row>
            <v-col cols="12" md="6">
              <v-text-field v-model="form.dictName" label="字典名称" :rules="dictNameRules" required variant="outlined"
                density="compact"></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-text-field v-model="form.dictValue" label="字典值" :rules="dictValueRules" required variant="outlined"
                density="compact"></v-text-field>
            </v-col>

            <v-col cols="12" md="6">
              <v-select v-model="form.izLock" :items="noYesOptions" label="是否内置" item-title="dictName"
                item-value="dictValue" variant="outlined" density="compact"></v-select>
            </v-col>

            <v-col cols="12" md="6">
              <v-text-field v-model.number="form.sortNo" label="排序" type="number" :min="1" :max="500"
                :rules="sortNoRules" required variant="outlined" density="compact"></v-text-field>
            </v-col>
          </v-row>
        </v-form>
      </v-card-text>

      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn @click="close">取消</v-btn>
        <v-btn color="primary" @click="save" :loading="saving">确定</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { doInsert, doUpdate } from '@/api/system/dict/dictDetailManagement';
import { isName, isNull } from '@/utils/validate';
import { useMessage } from '@/composables/useMessage';

const { proxy } = getCurrentInstance();
const { success: showSuccess, error: showError } = useMessage();

// 响应式数据
const dialogFormVisible = ref(false);
const valid = ref(true);
const saving = ref(false);
const title = ref('');
const formRef = ref();

const form = ref({
  typeId: '',
  typeCode: '',
  dictName: '',
  dictValue: '',
  izLock: '0',
  sortNo: 1,
  version: 0
});

const noYesOptions = ref([]);

// 验证规则
const dictNameRules = [
  v => !!v || '请输入名称'];

const dictValueRules = [
  v => !!v || '请输入值'
];

const sortNoRules = [
  v => !!v || '请输入排序',
  v => (v >= 1 && v <= 500) || '排序必须在1-500之间'
];

// 定义 emits
const emit = defineEmits(['fetchData']);

onMounted(() => {
  // 获取字典数据
  noYesOptions.value = proxy?.$getDictList('no_yes') || [];
});

/**
 * 显示新增对话框
 */
const showInsert = (dictType) => {
  title.value = '字典类型 - 添加';
  form.value = {
    typeId: dictType.typeId,
    typeCode: dictType.typeCode,
    dictName: '',
    dictValue: '',
    izLock: '0',
    sortNo: 1,
    version: 0
  };
  dialogFormVisible.value = true;
};

/**
 * 显示编辑对话框
 */
const showUpdate = (row) => {
  title.value = '字典类型 - 编辑';
  form.value = { ...row };
  dialogFormVisible.value = true;
};

/**
 * 关闭对话框
 */
const close = () => {
  dialogFormVisible.value = false;
  formRef.value?.resetValidation();
  form.value = {
    typeId: '',
    typeCode: '',
    dictName: '',
    dictValue: '',
    izLock: '0',
    sortNo: 1,
    version: 0
  };
};

/**
 * 保存数据
 */
const save = async () => {
  if (!formRef.value) return;

  const { valid: isValid } = await formRef.value.validate();
  if (!isValid) return;

  saving.value = true;

  try {
    let response;
    if (!isNull(form.value.id)) {
      // 修改
      response = await doUpdate(form.value);
    } else {
      // 新增
      response = await doInsert(form.value);
    }

    showSuccess(response.msg || '保存成功');
    emit('fetchData');
    close();
  } catch (error) {
    console.error('保存失败:', error);
    showError('保存失败');
  } finally {
    saving.value = false;
  }
};

// 暴露方法
defineExpose({
  showInsert,
  showUpdate
});
</script>
